﻿ #include <netdb.h>
 #include <stdio.h>
 #include "common_func.h"
 #include "unix_client.h"
 #include <stdlib.h>

static int sockFd = -1;

int InitUdpClient()
{

	TSockAddrUn unadr;
	TSockAddr   *pSockAddr = NULL;

	bzero(&unadr,sizeof(unadr));

	char tmpPath[] = "/tmp/unix_XXXX";
	char *tmpName = mktemp(tmpPath);

	unadr.sun_family = AF_LOCAL;
	strcpy(unadr.sun_path, tmpName);

	pSockAddr = (TSockAddr *)&unadr;


	/* 创建本地socket */
	sockFd = socket(AF_LOCAL, SOCK_DGRAM, 0);//数据包方式
	if ( sockFd <= 0)
	{
	    perror("CUdpClient:: socket error");
	    return sockFd;
	}
	
	unlink(tmpPath);

	/* 绑定监听口 */
    //setSocketAttr(sockFd);
	int iRet = bind(sockFd,pSockAddr, sizeof(TSockAddr));
	if (iRet != 0)
	{
	    perror("bind error");
		close(sockFd);
		return -1;
	}

    return sockFd;
}

//返回0 超时  timeOut-超时时间
int UnixRead(char *recvBuf, int len, int timeOut)
{
	int nRead = readable_timeo(sockFd, timeOut);
	if ( nRead <= 0 )
	{
		printf("UnixRead, read time out!\n");
		return 0;
	}

	bzero(recvBuf, len);
	
	nRead = recvfrom(sockFd, recvBuf, len, 0, 0, 0);
	if ( nRead <= 0 )
	{		
		perror("UnixRead read error:");
		return 0;
	}
	
	return nRead;
}


int UnixSend(const void *data, int len)
{
	TSockAddrUn unadr;
	TSockAddr   *pSockAddr = NULL;

	bzero(&unadr,sizeof(unadr));
	
	unadr.sun_family = AF_LOCAL;
	strcpy(unadr.sun_path, UNIX_SOCKET_PATH);

	pSockAddr = (TSockAddr *)&unadr;
	socklen_t socklen  = sizeof(TSockAddrUn);

	return sendto(sockFd, data, len, 0, pSockAddr, socklen);
}

#ifdef _TEST_
 int main( int argc, char **argv )
 {
	 int sockFd = InitUdpClient();
	 
	 int nRead = 0;
	 //MsgInfoSt stMsgInfo;
	 //stMsgInfo.type = 1;
	 
	 //stMsgInfo.cmd = (int)atoi(argv[1]);
	 
	 //return UnixSend(&stMsgInfo, sizeof(MsgInfoSt));
	 
	 const char *sendMsg = "hello";
	 char recvBuf[1024] = {0};
	 while(1)
	 {
			
		nRead = UnixSend(sendMsg, strlen(sendMsg));
		printf("send %d data: %s\n", nRead, sendMsg);
	
		nRead = UnixRead(recvBuf, 1024, 5);
		printf("recv %d data: %s\n", nRead, recvBuf);
		sleep(2);
	 }
	 return 0;
 }
 #endif
 
 
 
